<template>
  <div class="gantt-container">
    <div class="search">
      <el-form v-show="showSearch" ref="queryForm" :model="queryParams" inline :label-width="100">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable size="small" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="计划开始日期" prop="psr">
          <el-date-picker
            v-model="queryParams.psr"
            size="small"
            type="daterange"
            range-separator="-"
            start-placeholder="时间范围开始"
            value-format="yyyy-MM-dd"
            end-placeholder="时间范围结束"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item class="fr">
          <el-button-group>
            <el-button type="primary" :plain="gantt" size="mini" icon="el-icon-s-order" @click="handleChange('table')">列表</el-button>
            <el-button type="primary" :plain="!gantt" size="mini" icon="el-icon-s-unfold" @click="handleChange('gantt')">甘特图</el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </div>
    <div class="table">
      <el-table v-if="!gantt" v-loading="loading" :data="taskList" :border="tableBorder">
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="计划开始日期" align="center" prop="planStart" width="180">
          <template #default="{ row }">
            <span>{{ parseTime(row.planStart, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划结束日期" align="center" prop="planFinish" width="180">
          <template #default="{ row }">
            <span>{{ parseTime(row.planFinish, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际开始日期" align="center" prop="actualStart" width="180">
          <template #default="{ row }">
            <span>{{ parseTime(row.actualStart, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际结束日期" align="center" prop="actualFinish" width="180">
          <template #default="{ row }">
            <span>{{ parseTime(row.actualFinish, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="{ row }">
            <dict-tag :options="dict.type.agriculture_batch_task_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #header>
            <el-button
              v-if="mode === 0"
              class="width-90"
              type="primary"
              :disabled="!checkPermi(['agriculture:batchTask:add'])"
              size="mini"
              plain
              icon="el-icon-plus"
              @click="handleAdd"
              >新增任务</el-button
            >
            <span v-else>操作</span>
          </template>
          <template #default="{ row }">
            <el-button
              v-if="mode !== 0"
              v-hasPermi="['agriculture:batchTask:query']"
              size="small"
              type="primary"
              class="padding-5"
              plain
              icon="el-icon-edit"
              @click="handleTask(row.taskId)"
              >任务处理</el-button
            >
            <el-button
              v-if="mode === 0"
              v-hasPermi="['agriculture:batchTask:edit']"
              size="small"
              type="primary"
              class="padding-5"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
              >修改</el-button
            >
            <el-button
              v-if="mode === 0"
              v-hasPermi="['agriculture:batchTask:remove']"
              size="small"
              type="danger"
              class="padding-5"
              icon="el-icon-delete"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <gantt v-else class="gantt" :tasks="tasks"></gantt>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </div>
    <!-- 添加或修改批次任务对话框 -->
    <el-dialog v-model="open2" :title="title2" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="计划开始日期" prop="planStart">
          <el-date-picker v-model="form.planStart" clearable class="w100" type="date" value-format="yyyy-MM-dd" placeholder="选择计划开始日期" />
        </el-form-item>
        <el-form-item label="计划结束日期" prop="planFinish">
          <el-date-picker v-model="form.planFinish" clearable class="w100" type="date" value-format="yyyy-MM-dd" placeholder="选择计划结束日期" />
        </el-form-item>
        <el-form-item label="任务详情" prop="taskDetail">
          <el-input v-model="form.taskDetail" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 任务详情对话框 -->
    <el-dialog v-model="open" :title="title" width="1100px" append-to-body @close="cancel">
      <task-detail :opr-type="oprType" :task-id="taskId" />
    </el-dialog>
  </div>
</template>

<script setup name="Task" lang="ts">
import { ref, watch, onMounted } from 'vue';
import { checkPermi } from '@/utils/permission';
import { listBatchTask, listBatchTaskOfMine, getBatchTask, addBatchTask, updateBatchTask, delBatchTask } from '@/api/agriculture/batchTask';
import TaskDetail from '@/views/components/TaskDetail/index.vue';
// import Gantt from '@/components/Gantt.vue';

const props = defineProps({
  batchId: [Number],
  tableBorder: {
    type: Boolean,
    default: false
  },
  mode: {
    type: Number,
    default: 0
  }
});

const emit = defineEmits();

//gantt
const gantt = ref(false);

// 遮罩层
const loading = ref(true);

// 显示搜索条件
const showSearch = ref(true);

// 总条数
const total = ref(0);

// 批次任务表格数据
const taskList = ref([]);

const open = ref(false);
const title = ref('');

//任务id
const taskId = ref(null);

//操作类型：add和update
const oprType = ref(null);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  taskName: null,
  planStart: null,
  planFinish: null,
  batchId: props.batchId,
  psr: null,
  params: {
    planStartStart: null,
    planStartEnd: null
  }
});

const tasks = ref({
  data: []
});

const title2 = ref('');
const open2 = ref(false);

// 表单参数
const form = ref({});

// 表单校验
const rules = ref({
  taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  planStart: [{ required: true, message: '计划开始日期不能为空', trigger: 'blur' }],
  planFinish: [{ required: true, message: '计划结束日期不能为空', trigger: 'blur' }]
});

watch(
  () => props.batchId,
  (n, o) => {
    queryParams.value.batchId = n;
    getList();
  }
);

onMounted(() => {
  getList();
  // gantt.value.config.columns = [{ name: 'text', label: '任务名称', tree: true, width: '200' }];

  // gantt.value.attachEvent('onTaskDblClick', (id, e) => {
  //   handleTask(Number(id));
  //   return false;
  // });
});

/** 查询批次任务列表 */
const getList = async () => {
  loading.value = true;
  const { psr } = queryParams.value;
  if (psr && Array.isArray(psr) && psr.length === 2) {
    queryParams.value.params.planStartStart = psr[0];
    queryParams.value.params.planStartEnd = psr[1];
  } else {
    queryParams.value.params.planStartStart = null;
    queryParams.value.params.planStartEnd = null;
  }

  let response;
  if (props.mode === 0 || props.mode === 2) {
    response = await listBatchTask(queryParams.value);
  } else if (props.mode === 1) {
    response = await listBatchTaskOfMine(queryParams.value);
  }

  taskList.value = response.rows;
  total.value = response.total;
  loading.value = false;
  tasks.value.data = taskList.value.map((item) => ({
    text: item.taskName,
    id: item.taskId,
    start_date: new Date(`${item.planStart} 00:00:00`),
    end_date: new Date(`${item.planFinish} 23:59:59`),
    color: '#2b7'
  }));
};

// 取消按钮
const cancel2 = () => {
  open2.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    taskId: null,
    batchId: null,
    taskName: null,
    planStart: null,
    planFinish: null,
    actualStart: null,
    actualFinish: null,
    taskDetail: null,
    taskImages: null,
    taskVideos: null,
    remark: null,
    status: '0',
    orderNum: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    taskName: null,
    planStart: null,
    planFinish: null,
    batchId: props.batchId,
    psr: null,
    params: {
      planStartStart: null,
      planStartEnd: null
    }
  };
  handleQuery();
};

/** 处理任务按钮 */
const handleTask = (taskIdValue) => {
  taskId.value = taskIdValue;
  oprType.value = 'update';
  open.value = true;
  title.value = '编辑任务';
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open2.value = true;
  title2.value = '添加批次任务';
  form.value.batchId = props.batchId;
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  const response = await getBatchTask(row.taskId);
  form.value = response.data;
  open2.value = true;
  title2.value = '修改批次任务';
};

/** 提交按钮 */
const submitForm = async () => {
  const formRef = ref(null);
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (form.value.taskId) {
        await updateBatchTask(form.value);
        ElMessage.success('修改成功');
      } else {
        await addBatchTask(form.value);
        ElMessage.success('新增成功');
      }
      open2.value = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  await ElMessageBox.confirm('是否确认删除批次任务编号为"' + row.taskId + '"的数据项？');
  await delBatchTask(row.taskId);
  getList();
  ElMessage.success('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  download('agriculture/task/export', { ...queryParams.value }, `task_${new Date().getTime()}.xlsx`);
};

/** 处理切换按钮操作 */
const handleChange = (type) => {
  if (type === 'gantt') {
    gantt.value = true;
  } else {
    gantt.value = false;
  }
};

const cancel = () => {
  getList();
};
</script>

<style lang="scss" scoped>
.gantt-container {
  height: 100%;
  .table {
    background: #fff;
    padding: 0 10px;
    height: calc(100% - 70px - 70px);
    .gantt {
      overflow: hidden;
      position: relative;
      height: 100%;
    }
  }
  .search {
    background: #fff;
    height: 70px;
    display: flex;
    align-items: center;
    position: sticky;
    top: 0px;
    z-index: 2;
  }
}

.pagination-container {
  height: 50px;
}

.search ::v-deep .el-form-item {
  margin-bottom: 0;
}

.search ::v-deep .el-form {
  flex: 1;
}
</style>
